import { request } from "@/utils/service"
/**
 * 创建一个a标签，并做下载点击事件
 *  */
export function downloadFile(blob, fileName) {
  const link = document.createElement("a")
  link.href = window.URL.createObjectURL(blob)
  link.download = fileName
  // 此写法兼容可火狐浏览器
  document.body.appendChild(link)
  const evt = document.createEvent("MouseEvents")
  evt.initEvent("click", false, false)
  link.dispatchEvent(evt)
  document.body.removeChild(link)
}
/**
 * // 将Base64文件转为 Blob
 * @param data
 * @returns
 */

export function buildBlobByByte(data) {
  const raw = window.atob(data)
  const rawLength = raw.length
  const uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array])
}
/**
 * // 二进制数组 生成文件
 * @param data
 * @param fileName
 */
export function downloadFileByByte(data, fileName) {
  const blob = buildBlobByByte(data)
  downloadFile(blob, fileName)
}


//请求后端获取文件
export const getFile = async (url, name) => {
  try {
    const response = await request({
      url,
      method: "POST",
      responseType: 'blob' // 在这里指定
    })
    // 处理文件下载
    const blob = new Blob([response]);
    const fileName = `${name}.xlsx`;
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(downloadUrl);

    // console.log(response);

    // downloadFileByByte(blob,name)
  } catch (error) {
    console.error('导出失败:', error);
  }
}